<template>
  <view class="search-bar" :class="{ 'search-bar--focused': isFocused }">
    <view class="search-input-container">
      <view class="search-icon">
        <uni-icons type="search" size="18" color="var(--text-color-placeholder)"></uni-icons>
      </view>
      
      <input
        class="search-input"
        type="text"
        :placeholder="placeholder"
        :value="modelValue"
        :maxlength="maxLength"
        :disabled="disabled"
        @input="handleInput"
        @focus="handleFocus"
        @blur="handleBlur"
        @confirm="handleConfirm"
      />
      
      <view v-if="showClearButton && modelValue" class="clear-button" @click="handleClear">
        <uni-icons type="clear" size="16" color="var(--text-color-placeholder)"></uni-icons>
      </view>
      
      <view v-if="showVoiceButton" class="voice-button" @click="handleVoiceSearch">
        <uni-icons type="mic" size="18" color="var(--text-color-placeholder)"></uni-icons>
      </view>
    </view>
    
    <!-- 搜索建议下拉框 -->
    <view v-if="showSuggestions && suggestions.length > 0" class="suggestions-dropdown">
      <scroll-view scroll-y class="suggestions-list" :style="{ maxHeight: suggestionsMaxHeight + 'px' }">
        <view
          v-for="(suggestion, index) in suggestions"
          :key="index"
          class="suggestion-item"
          @click="handleSelectSuggestion(suggestion)"
        >
          <view class="suggestion-icon">
            <uni-icons 
              :type="suggestion.type === 'history' ? 'clock' : 'search'" 
              size="14" 
              color="var(--text-color-placeholder)"
            ></uni-icons>
          </view>
          <text class="suggestion-text">{{ suggestion.text }}</text>
          <view 
            v-if="suggestion.type === 'history'" 
            class="suggestion-delete"
            @click.stop="handleDeleteSuggestion(index)"
          >
            <uni-icons type="clear" size="12" color="var(--text-color-placeholder)"></uni-icons>
          </view>
        </view>
      </scroll-view>
      
      <view v-if="showClearHistory" class="suggestions-footer">
        <text class="clear-history-btn" @click="handleClearHistory">清空搜索历史</text>
      </view>
    </view>
    
    <!-- 热门搜索标签 -->
    <view v-if="showHotTags && hotTags.length > 0 && !isFocused" class="hot-tags">
      <text class="hot-tags-title">热门搜索</text>
      <view class="hot-tags-list">
        <text
          v-for="(tag, index) in hotTags"
          :key="index"
          class="hot-tag"
          @click="handleSelectHotTag(tag)"
        >
          {{ tag }}
        </text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';

interface Suggestion {
  text: string;
  type: 'history' | 'suggestion';
}

interface Props {
  modelValue: string;
  placeholder?: string;
  maxLength?: number;
  disabled?: boolean;
  showClearButton?: boolean;
  showVoiceButton?: boolean;
  showSuggestions?: boolean;
  suggestions?: Suggestion[];
  suggestionsMaxHeight?: number;
  showClearHistory?: boolean;
  showHotTags?: boolean;
  hotTags?: string[];
  debounceTime?: number;
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请输入搜索关键词',
  maxLength: 50,
  disabled: false,
  showClearButton: true,
  showVoiceButton: false,
  showSuggestions: true,
  suggestions: () => [],
  suggestionsMaxHeight: 200,
  showClearHistory: true,
  showHotTags: true,
  hotTags: () => [],
  debounceTime: 300,
});

const emit = defineEmits<{
  'update:modelValue': [value: string];
  search: [keyword: string];
  focus: [];
  blur: [];
  clear: [];
  voiceSearch: [];
  selectSuggestion: [suggestion: Suggestion];
  deleteSuggestion: [index: number];
  clearHistory: [];
  selectHotTag: [tag: string];
}>();

const isFocused = ref(false);
let debounceTimer: number | null = null;

const handleInput = (e: any) => {
  const value = e.detail.value;
  emit('update:modelValue', value);
  
  // 防抖处理
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
  
  debounceTimer = setTimeout(() => {
    if (value.trim()) {
      emit('search', value.trim());
    }
  }, props.debounceTime);
};

const handleFocus = () => {
  isFocused.value = true;
  emit('focus');
};

const handleBlur = () => {
  // 延迟失焦，避免点击建议项时立即隐藏
  setTimeout(() => {
    isFocused.value = false;
    emit('blur');
  }, 200);
};

const handleConfirm = () => {
  if (props.modelValue.trim()) {
    emit('search', props.modelValue.trim());
  }
};

const handleClear = () => {
  emit('update:modelValue', '');
  emit('clear');
  
  // 清除防抖定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
};

const handleVoiceSearch = () => {
  emit('voiceSearch');
  
  // 触觉反馈
  uni.vibrateShort({
    type: 'light'
  });
};

const handleSelectSuggestion = (suggestion: Suggestion) => {
  emit('update:modelValue', suggestion.text);
  emit('selectSuggestion', suggestion);
  emit('search', suggestion.text);
  isFocused.value = false;
};

const handleDeleteSuggestion = (index: number) => {
  emit('deleteSuggestion', index);
  
  // 触觉反馈
  uni.vibrateShort({
    type: 'light'
  });
};

const handleClearHistory = () => {
  uni.showModal({
    title: '确认清空',
    content: '确定要清空所有搜索历史吗？',
    success: (res) => {
      if (res.confirm) {
        emit('clearHistory');
        uni.showToast({ title: '已清空搜索历史', icon: 'success' });
      }
    }
  });
};

const handleSelectHotTag = (tag: string) => {
  emit('update:modelValue', tag);
  emit('selectHotTag', tag);
  emit('search', tag);
};
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.search-bar {
  position: relative;
  
  &--focused {
    .search-input-container {
      border-color: var(--primary-color);
      box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.1);
    }
  }
}

.search-input-container {
  display: flex;
  align-items: center;
  background-color: var(--card-background);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-large);
  padding: var(--spacing-sm) var(--spacing-md);
  transition: all var(--transition-normal) ease;
  
  .search-icon {
    margin-right: var(--spacing-sm);
    flex-shrink: 0;
  }
  
  .search-input {
    flex: 1;
    font-size: var(--font-size-md);
    color: var(--text-color);
    background: transparent;
    border: none;
    outline: none;
    
    &::placeholder {
      color: var(--text-color-placeholder);
    }
    
    &:disabled {
      color: var(--text-color-disabled);
    }
  }
  
  .clear-button,
  .voice-button {
    margin-left: var(--spacing-sm);
    padding: var(--spacing-xs);
    border-radius: var(--border-radius-round);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all var(--transition-fast) ease;
    
    &:active {
      transform: scale(0.9);
      background-color: var(--background-color-light);
    }
  }
}

// 搜索建议下拉框
.suggestions-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background-color: var(--card-background);
  border: 1px solid var(--border-color);
  border-top: none;
  border-radius: 0 0 var(--border-radius-large) var(--border-radius-large);
  box-shadow: var(--shadow);
  z-index: var(--z-index-dropdown);
  animation: slideDown var(--transition-fast) ease;
}

.suggestions-list {
  max-height: 200px;
}

.suggestion-item {
  display: flex;
  align-items: center;
  padding: var(--spacing-md);
  border-bottom: 1px solid var(--border-color-light);
  cursor: pointer;
  transition: background-color var(--transition-fast) ease;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background-color: var(--background-color-light);
  }
  
  .suggestion-icon {
    margin-right: var(--spacing-sm);
    flex-shrink: 0;
  }
  
  .suggestion-text {
    flex: 1;
    font-size: var(--font-size-md);
    color: var(--text-color);
    @include text-ellipsis;
  }
  
  .suggestion-delete {
    margin-left: var(--spacing-sm);
    padding: var(--spacing-xs);
    border-radius: var(--border-radius-round);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all var(--transition-fast) ease;
    
    &:active {
      transform: scale(0.9);
      background-color: var(--background-color-light);
    }
  }
}

.suggestions-footer {
  padding: var(--spacing-sm) var(--spacing-md);
  border-top: 1px solid var(--border-color-light);
  text-align: center;
  
  .clear-history-btn {
    font-size: var(--font-size-sm);
    color: var(--text-color-secondary);
    cursor: pointer;
    
    &:active {
      color: var(--primary-color);
    }
  }
}

// 热门搜索标签
.hot-tags {
  margin-top: var(--spacing-md);
  
  .hot-tags-title {
    font-size: var(--font-size-sm);
    color: var(--text-color-secondary);
    margin-bottom: var(--spacing-sm);
    display: block;
  }
  
  .hot-tags-list {
    display: flex;
    flex-wrap: wrap;
    gap: var(--spacing-sm);
    
    .hot-tag {
      padding: var(--spacing-xs) var(--spacing-sm);
      background-color: var(--background-color-light);
      color: var(--text-color-secondary);
      font-size: var(--font-size-sm);
      border-radius: var(--border-radius);
      cursor: pointer;
      transition: all var(--transition-fast) ease;
      
      &:active {
        background-color: var(--primary-color);
        color: #ffffff;
        transform: scale(0.95);
      }
    }
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>